import UIKit

//如何过滤集合中的 nil 值 https://www.zhihu.com/people/biao-26/posts?page=12

extension Collection {
    func removeNils1<T>() -> [T] where Element == T? {
        compactMap { p in
            p
        }
    }
}

// 方法1:
let array = [1, 2, nil, 3, 4]
print(array.compactMap({ $0 }))
print(array.removeNils1())


//方法2:
extension Collection {
    func removeNils2<T>() -> [T] where Element == T? {
        var array: [T] = []
        for value in self {
            if let value {
                array.append(value)
            }
        }
        return array
    }
}

let array2 = [3,5,nil,nil,230]
print(array2.removeNils2())


let possibleNumbers = ["1", "2", "three", "///4///", "5"]


let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]
print(mapped)

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]
print(compactMapped)
